import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { routes } from './index';
import { RouteUtils } from './utils';

/**
 * 应用路由组件
 * 使用React Router实现路由功能
 */
const AppRouter = () => {
  // 渲染路由组件
  const renderRoute = (route, index) => {
    // 处理重定向
    if (route.redirect) {
      return (
        <Route 
          key={index} 
          path={route.path} 
          element={<Navigate to={route.redirect} replace />} 
        />
      );
    }

    // 处理普通路由
    if (route.component) {
      const Component = route.component;
      return (
        <Route 
          key={index} 
          path={route.path} 
          element={<Component />} 
          exact={route.exact}
        />
      );
    }

    // 处理子路由
    if (route.routes && route.routes.length > 0) {
      return (
        <Route key={index} path={route.path}>
          {route.routes.map((subRoute, subIndex) => 
            renderRoute(subRoute, `${index}-${subIndex}`)
          )}
        </Route>
      );
    }

    return null;
  };

  return (
    <Router>
      <RouteGuard>
        <div className="App">
          <main className="main-content">
            <Routes>
              {routes.map((route, index) => renderRoute(route, index))}
            </Routes>
          </main>
        </div>
      </RouteGuard>
    </Router>
  );
};

/**
 * 路由守卫组件
 * 用于处理路由权限控制和页面元信息设置
 */
export const RouteGuard = ({ children }) => {
  React.useEffect(() => {
    // 获取当前路由信息
    const routeInfo = RouteUtils.getCurrentRouteInfo();
    
    // 查找当前路由配置
    const currentRoute = RouteUtils.findRouteByPath(routes, routeInfo.pathname);
    
    if (currentRoute && currentRoute.meta) {
      // 设置页面元信息
      RouteUtils.setPageMeta(currentRoute.meta);
      
      // 记录路由历史
      RouteUtils.saveRouteHistory({
        path: routeInfo.pathname,
        title: currentRoute.meta.title || currentRoute.name || '未知页面',
        timestamp: Date.now(),
        query: Object.fromEntries(routeInfo.query),
      });
    }
  }, []);

  return children;
};

export default AppRouter;
